//
//  MVDetailsViewController.m
//  DayByDay
//
//  Created by dllo on 16/5/26.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "MVDetailsViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "STKAudioPlayerHandle.h"
#import "SessionManager.h"

@interface MVDetailsViewController ()

@property (strong, nonatomic) IBOutlet UIView *smallView;
- (IBAction)startBtnAction:(id)sender;
@property (strong, nonatomic) IBOutlet UILabel *startLabel;
@property (strong, nonatomic) IBOutlet UILabel *endLabel;
- (IBAction)downLoadBtn:(UIButton *)sender;
- (IBAction)timeSlider:(id)sender;
@property (strong, nonatomic) IBOutlet UISlider *timeSlider;
@property (nonatomic, strong)AVPlayer *player;
@property (nonatomic, strong)NSTimer *timer;
@property (strong, nonatomic) IBOutlet UIView *containerView;
@property (nonatomic, assign) BOOL isTap;
@property (nonatomic, strong)AVPlayerLayer *playerLayer;
@property (nonatomic, strong)SessionManager *manager;
@property (nonatomic, assign)NSInteger currentMV;

@end

@implementation MVDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self getMV];
    [self createPlayer];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    UISwipeGestureRecognizer *swip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
    swip.direction = UISwipeGestureRecognizerDirectionRight;
    UISwipeGestureRecognizer *swipLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipLeft:)];
    swipLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.containerView addGestureRecognizer:swipLeft];
    
//    UISwipeGestureRecognizer
    [self.containerView addGestureRecognizer:swip];
    [self.containerView addGestureRecognizer:tap];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"player" object:self.player];
    self.smallView.alpha = 0;
    STKAudioPlayerHandle *stk = [STKAudioPlayerHandle shareSTKAudioPlayerHandle];
    [stk.audioPlayer pause];
    [self addNotificationCenters];
    UIButton *button = [self.view viewWithTag:88888];
    button.hidden = YES;
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getMV:) name:@"MVValue1" object:nil];
//    [self getMV];
}

- (void)getMV {
    NSIndexPath *indexPath = self.array.lastObject;
    NSLog(@"%ld",[self.array.lastObject row]);
    self.currentMV = indexPath.row;
    [self.array removeLastObject];
    self.model = [[self.array[indexPath.row] mvList] lastObject];
    
}

- (void)swipLeft:(UISwipeGestureRecognizer *)swip {
    NSLog(@"222");
    [self nextMV];
}

- (void)panAction:(UIPanGestureRecognizer *)pan {
    NSLog(@"111111");
    [self lastMV];
    
}

- (void)tapAction:(UITapGestureRecognizer *)tap {
    if (self.smallView.alpha == 0) {
        self.smallView.alpha = 0.5;
        self.navigationController.navigationBar.hidden = NO;
    } else {
        self.smallView.alpha = 0;
        self.navigationController.navigationBar.hidden = YES;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"消失了");
    AppDelegate *tempDele = [[UIApplication sharedApplication] delegate];
    [tempDele.JHJTabBar hiddenTabBarWithAnimation:NO];
    // 强制横屏
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationLandscapeRight;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
    self.smallView.alpha = 0.5;
}

- (void)createPlayer {
    self.player = [AVPlayer playerWithPlayerItem:[self createPlayItemWithUrl:self.model.url]];
    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.player.volume = 2;
    self.player.rate = 1;
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.bounds = CGRectMake(0, 0, WIDTH, HEIGHT);
    layer.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    self.playerLayer = layer;
     [self.containerView.layer insertSublayer:layer atIndex:0];
    [self.player play];
    [self addObserverWithPlayItemTime:self.player.currentItem];

    
}
- (void)sliderAction:(UISlider *)slider {
    
}
- (AVPlayerItem *) createPlayItemWithUrl:(NSString *)url{
    NSLog(@"%@",self.model.url);
    AVAsset *asset = [AVAsset assetWithURL:[NSURL URLWithString:url]];
    AVPlayerItem *playItem = [AVPlayerItem playerItemWithAsset:asset];
//    [self addObserverWithPlayItemTime:playItem];
    
    [playItem addObserver:self forKeyPath:@"status" options:NSKeyValueChangeNewKey||NSKeyValueChangeOldKey context:nil];
    [playItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueChangeNewKey || NSKeyValueChangeOldKey context:nil];
    return playItem;
}

#pragma mark - 观察者 观察播放完毕 观察屏幕旋转
- (void)addNotificationCenters {
    
    //  注册观察者用来观察，是否播放完毕
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    //  注册观察者来观察屏幕的旋转
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}

#pragma mark 播放结束后的代理回调
- (void)moviePlayDidEnd:(NSNotification *)notify
{
    
    NSLog(@"播放结束触发");
    
}

#pragma mark - 横屏 竖屏的时候frame的设置
- (void)statusBarOrientationChange:(NSNotification *)notification {
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
        NSLog(@"%f,%f",self.playerLayer.frame.origin.x, self.playerLayer.frame.origin.y);
        NSLog(@"%f,%f,%f,%f",self.playerLayer.bounds.origin.x,self.playerLayer.bounds.origin.y,self.playerLayer.bounds.size.width,self.playerLayer.bounds.size.height);
    if (orientation == UIInterfaceOrientationLandscapeRight) {
        
        NSLog(@"向右横屏");
        [self setPlayerLayerFrame];
    }
    if (orientation == UIInterfaceOrientationLandscapeLeft) {
        
        NSLog(@"向左横屏");
        [self setPlayerLayerFrame];
        
    }
    if (orientation == UIInterfaceOrientationPortrait) {
        
        NSLog(@"竖屏");
        [self setVerticalFrame];
    }
}

//  横屏的时候frame
- (void)setPlayerLayerFrame {
    
    self.playerLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    
    
}

//  竖屏的时候frame
- (void)setVerticalFrame {
    
    self.playerLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    
}



- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        NSLog(@"askfklsdjfklsdjfslkfjslkdfjs;lfjlsdfjksdfjlsdk;fjlsdfjsld;fjl;sdjf");
        AVPlayerItemStatus status = [[change objectForKey:keyPath] intValue];
//        NSLog(@"%d",status);
        if(status==AVPlayerItemStatusReadyToPlay || status == 0){
            NSLog(@"正在播放...，视频总长度:%.2f",CMTimeGetSeconds(self.player.currentItem.duration));
            self.endLabel.text = [NSString stringWithFormat:@"0%d:%.2f",(int)CMTimeGetSeconds(self.player.currentItem.duration) / 60, CMTimeGetSeconds(self.player.currentItem.duration) - (int)CMTimeGetSeconds(self.player.currentItem.duration)];
            //            self.Slider.maximumValue = CMTimeGetSeconds(self.player.currentItem.duration);
            
            //            NSLog(@"isdfjk");
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSArray *array = self.player.currentItem.loadedTimeRanges;
        CMTimeRange time = [array.firstObject CMTimeRangeValue]; // 本次缓冲时间范围.
        CGFloat currentLoaded = CMTimeGetSeconds(time.start);
        CGFloat durationLoaded = CMTimeGetSeconds(time.duration);
        NSTimeInterval totalBuffer = currentLoaded + durationLoaded;//缓冲总长度
        NSLog(@"共缓冲了%.2f",totalBuffer);
        CMTimeRange lastTime = [array.lastObject CMTimeRangeValue];
        CGFloat lastSeconds = CMTimeGetSeconds(lastTime.start);
        CGFloat lastDr = CMTimeGetSeconds(lastTime.duration);
        NSLog(@"%.2f, %.2f",lastSeconds, lastDr);
    }
}

- (void)removeObserverWithItem:(AVPlayerItem *)playItem {
    [playItem removeObserver:self forKeyPath:@"status"];
    [playItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    
}

- (void)addObserverWithPlayItemTime:(AVPlayerItem *)playItem {
    MVDetailsViewController *detialVC = self;
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        detialVC.startLabel.text = [NSString stringWithFormat:@"0%d:%.2f",(int)CMTimeGetSeconds(time) / 60, CMTimeGetSeconds(time) - 60 * (int)(CMTimeGetSeconds(time) / 60)];
        detialVC.timeSlider.value = CMTimeGetSeconds(time) / CMTimeGetSeconds(detialVC.player.currentItem.duration);
        if (CMTimeGetSeconds(time) == CMTimeGetSeconds(playItem.duration)) {
            [detialVC nextMV];
        }
//        NSLog(@"%f",CMTimeGetSeconds(self.player.currentItem.duration));
    }];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self removeObserverWithItem:self.player.currentItem];
    
    [self.player replaceCurrentItemWithPlayerItem:nil];
    self.player = nil;
    STKAudioPlayerHandle *stk = [STKAudioPlayerHandle shareSTKAudioPlayerHandle];
    stk.isAVPlayer = NO;
 // 强制设置竖屏
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
    NSLog(@"jfjfjfjfjfjf");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
// 下一首上一首
- (void)nextMV {
    self.currentMV++;
    if (self.currentMV == self.array.count) {
        self.currentMV = 0;
    }
    NSLog(@"%ld",self.currentMV);
    NSLog(@"%@",self.array) ;
    self.model = [[self.array[self.currentMV] mvList] lastObject];
    NSLog(@"%@",self.model.url);
    [self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    [self.player replaceCurrentItemWithPlayerItem:[self createPlayItemWithUrl:self.model.url]];
    [self.player play];
}

- (void)lastMV {
    self.currentMV--;
    if (self.currentMV == -1) {
        self.currentMV = self.array.count - 1;
    }
    self.model = [[self.array[self.currentMV] mvList] lastObject];
    [self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    [self.player replaceCurrentItemWithPlayerItem:[self createPlayItemWithUrl:self.model.url]];
    [self.player play];
}


- (IBAction)startBtnAction:(id)sender {
    UIButton *button = sender;
    if (!button.selected) {
        [self.player pause];
        [button setTitle:@"停止" forState:UIControlStateNormal];
    } else {
        [self.player play];
        [button setTitle:@"开始" forState:UIControlStateNormal];
    }
    button.selected = !button.selected;
}
- (IBAction)downLoadBtn:(UIButton *)sender {
    if (self.manager == nil) {
        self.manager = [SessionManager new];
        [self.manager downLoadUrl:self.model.url];
    }else {
        if (!sender.selected) {
            [self.manager pauseDownLoad];
        } else {
            [self.manager resumeDownLoad];
        }
        sender.selected = !sender.selected;
    }
} 

- (IBAction)timeSlider:(id)sender {
    UISlider *slider = sender;
    [self.player seekToTime:CMTimeMake(slider.value * CMTimeGetSeconds(self.player.currentItem.duration), 1)];
}
@end
